<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.account" placeholder="Account" clearable style="width: 180px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.appName" placeholder="App" clearable style="width: 180px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <DictGroupInput ref="dictGroupInput" :value.sync="listQuery.category" dict-group="account_category" placeholder="Category" class="filter-item" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">Search</el-button>
      <!-- show column popover -->
      <el-popover placement="bottom" width="150" trigger="click">
        <el-checkbox v-model="showRows.category" class="filter-item" @change="tableKey = tableKey + 1">Category</el-checkbox>
        <el-checkbox v-model="showRows.password" class="filter-item" @change="tableKey = tableKey + 1">Password</el-checkbox>
        <el-checkbox v-model="showRows.site" class="filter-item" @change="tableKey = tableKey + 1">Site</el-checkbox>
        <el-checkbox v-model="showRows.telephone" class="filter-item" @change="tableKey = tableKey + 1">Telephone</el-checkbox>
        <el-checkbox v-model="showRows.email" class="filter-item" @change="tableKey = tableKey + 1">Email</el-checkbox>
        <el-checkbox v-model="showRows.wx" class="filter-item" @change="tableKey = tableKey + 1">Wechat</el-checkbox>
        <el-checkbox v-model="showRows.qq" class="filter-item" @change="tableKey = tableKey + 1">QQ</el-checkbox>
        <el-checkbox v-model="showRows.secretQuestion" class="filter-item" @change="tableKey = tableKey + 1">Question</el-checkbox>
        <el-checkbox v-model="showRows.description" class="filter-item" @change="tableKey = tableKey + 1">Description</el-checkbox>

        <el-button slot="reference" v-waves class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-setting" />
      </el-popover>

      <router-link :to="{name:'CreateAccount'}">
        <el-button v-waves class="filter-item" type="primary" plain icon="el-icon-plus" />
      </router-link>
    </div>

    <el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%" @sort-change="sortChange">
      <el-table-column align="center" prop="id" label="ID" width="80" />
      <el-table-column v-if="showRows.category" align="center" prop="category" label="Category" />
      <el-table-column header-align="center" prop="appName" label="App" />
      <el-table-column header-align="center" prop="account" label="Account" />

      <el-table-column v-if="showRows.password" align="center" label="Password">
        <template slot-scope="scope">
          <span v-if="scope.row.decrypted">{{ scope.row.password }}</span>
          <el-button v-if="!scope.row.decrypted" type="warning" size="mini" icon="el-icon-view" plain @click="handleDecrypt(scope.row)" />
        </template>
      </el-table-column>

      <el-table-column v-if="showRows.site" header-align="center" label="Site" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-link :href="scope.row.loginUrl" type="primary" target="_blank">{{ scope.row.loginUrl }}</el-link>
        </template>
      </el-table-column>

      <el-table-column v-if="showRows.telephone" align="center" prop="telephone" label="Telephone" />
      <el-table-column v-if="showRows.email" header-align="center" prop="email" label="Email" />
      <el-table-column v-if="showRows.wx" align="center" prop="wx" label="Wechat" />
      <el-table-column v-if="showRows.qq" align="center" prop="qq" label="QQ" />
      <el-table-column v-if="showRows.secretQuestion" header-align="center" prop="secretQuestion" label="Question" />
      <el-table-column v-if="showRows.description" header-align="center" prop="description" label="Description" show-overflow-tooltip />

      <el-table-column width="180px" align="center" prop="modify_at" sortable="custom" label="UpdateTime">
        <template slot-scope="scope">
          <span>{{ scope.row.modifyAt | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>

      <el-table-column fixed="right" label="Actions" width="120">
        <template slot-scope="scope">
          <router-link :to="{name: 'EditAccount', params: scope.row }">
            <el-button type="primary" size="mini" icon="el-icon-edit" plain />
          </router-link>
          <el-button type="danger" size="mini" icon="el-icon-delete" plain @click="handleDelete(scope.row.id)" />
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.current" :limit.sync="listQuery.size" @pagination="getList" />
  </div>
</template>

<script>
import { fetchList, decryptAccountPassword, deleteAccountPassword } from '@/api/usr/account-password'
import { getSorts } from '@/utils/index'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { mapGetters } from 'vuex'
import DictGroupInput from '@/views/components/DictGroupInput'

export default {
  name: 'AccountList',
  components: { Pagination, DictGroupInput },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      showRows: {
        category: true,
        password: true,
        site: true,
        telephone: false,
        email: false,
        wx: false,
        qq: false,
        secretQuestion: false,
        description: false
      },
      list: null,
      total: 0,
      sort: {},
      listLoading: true,
      listQuery: {
        uid: undefined,
        account: undefined,
        appName: undefined,
        category: undefined,
        current: 1,
        size: 10,
        asc: undefined,
        desc: undefined
      }
    }
  },
  computed: {
    ...mapGetters(['uid', 'decryption'])
  },
  created() {
    this.listQuery.uid = this.uid
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery)
        .then(response => {
          this.list = response.result.list
          this.total = response.result.total
          this.listLoading = false
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.current = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      this.sort[prop] = undefined
      if (order) {
        this.sort[prop] = order !== 'descending'
      }
      const sort = getSorts(this.sort)
      this.listQuery.asc = sort.asc
      this.listQuery.desc = sort.desc
      this.handleFilter()
    },
    handleDelete(id) {
      this.$confirm('Confirm delete record?', 'Warning', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        deleteAccountPassword(id).then(response => {
          console.log(response)
          this.$message({
            type: 'success',
            message: 'deleted successfully!'
          })
          this.getList()
        })
      })
    },
    /**
     * 处理点击密码事件
     */
    handleDecrypt(row) {
      if (!row.decrypted) {
        if (!this.decryption) {
          this.$prompt('please input key', 'Tip', {
            confirmButtonText: 'Confrim',
            cancelButtonText: 'Cancel',
            inputPattern: /^[A-Za-z\d$@$!%*#?&]{6,}$/,
            inputErrorMessage: 'Invalid key'
          })
            .then(({ value }) => {
              this.getDecryption(row, value)
            })
            .catch(() => {})
        } else {
          this.getDecryption(row, this.decryption)
        }
      }
    },
    getDecryption(row, decryption) {
      decryptAccountPassword({ password: row.password, decryption }).then(res => {
        row.password = res.result
        row.decrypted = true
        this.tableKey += 1
        this.$store.dispatch('user/setDecryption', decryption)
      })
    }
  }
}
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
